package blog.controller;

import java.io.IOException;

import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import blog.entities.User;
import blog.service.UserService;
import blog.service.impl.UserServiceImpl;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.date.DateUtil;


@WebServlet("/login")
public class UserController extends HttpServlet {

	private UserService userService = new UserServiceImpl();
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 解决浏览器到服务器端中文编码不一致问题
		req.setCharacterEncoding("UTF-8");
		// 解决服务器端到浏览器中文编码不一致问题
		resp.setContentType("text/html;charset=utf-8");

		String option = req.getParameter("op");

		if (option != null) {
			try {
				Method method = getClass().getDeclaredMethod(option, HttpServletRequest.class, HttpServletResponse.class);
				method.setAccessible(true);
				method.invoke(this,req,resp);
			} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}


	/**
	 * 用于处理客户请求中的用户登录
	 * @param req 请求
	 * @param resp 响应
	 * @throws ServletException
	 * @throws IOException
	 */
	private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("login()");
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		System.out.println(username);
		System.out.println(password);
		// 获取客户端输入的验证码
		String code = req.getParameter("code");
		HttpSession session = req.getSession();
		Object genCode = session.getAttribute("genCode");

		if (!"".equals(code) && code.equals(genCode)) {
			System.out.println("输入正确");

			if ((username != null && password != null)) {
				// 区分是管理员还是普通成员
				if (username.equals("qipan")) {
					if (userService.userLogin(username, password) != null) {
						System.out.println("管理员登录成功");

						// Eclipse的写法
//					req.getRequestDispatcher("/WEB-INF/mgrCenter?option=mgrCenter").forward(req,resp);
						// 以下IDEA的写法
//					req.getRequestDispatcher("/mgrCenter?option=mgrCenter").forward(req,resp);
//						resp.sendRedirect(req.getContextPath() + "/mgrCenter?option=mgrCenter");
						session.setAttribute("session_user",username);
						req.setAttribute("privilege","administrator");
						req.getRequestDispatcher("/cookie?op=cookieMgr").forward(req,resp);

					}
				} else {
					User user = userService.userLogin(username, password);
					if (user != null) {
						System.out.println("普通成员登录成功");
						req.getSession().setAttribute("session_user",username);
//						req.getRequestDispatcher("/WEB-INF/success.jsp").forward(req,resp);
						req.setAttribute("privilege","member");
						req.getRequestDispatcher("/cookie?op=cookieMgr").forward(req,resp);
						// 为什么以下就会出现404
//					resp.sendRedirect(req.getContextPath() + "/WEB-INF/success.jsp");
					} else {
						System.out.println("普通成员登录失败");
						PrintWriter writer = resp.getWriter();
						writer.print("<h3>登录失败,请重试</h3>");
						writer.close();
					}
				}
			}
		} else {
			PrintWriter writer = resp.getWriter();
			writer.write("输入错误");
			writer.close();
		}

	}

	private void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("logout()");
		HttpSession session = req.getSession();
		Object session_user = session.getAttribute("session_user");
		if (session_user != null) {
			session.removeAttribute("session_user");
			// 使所有session中的object失效
			session.invalidate();
		}
		resp.sendRedirect(req.getContextPath() + "/index.jsp");
	}

	/**
	 * 用于处理客户请求中的用户注册
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	private void register(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException  {
		System.out.println("register()");
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		if(req.getParameter("register") != null && req.getParameter("register").equals("注册")) {
			System.out.println("注册过程...");
			System.out.println(userService.userRegister(username,password));
			System.out.println("登录过程...");
			User user = userService.userLogin(username, password);
			System.out.println(user);
			resp.getWriter().write("<p>login success...</p>" + "成功");
		}
	}

	private void checkCode(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException  {
		System.out.println("checkCode()");
		LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 20, 4, 11);
		req.getSession().setAttribute("genCode",lineCaptcha.getCode());
		System.out.println(lineCaptcha.getCode());
		lineCaptcha.write(resp.getOutputStream());
	}

}
